//
//  Album.m
//  UI_15_下午练习_collectionView封装轮播图
//
//  Created by li cheng on 16/8/4.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "Album.h"
#import "UIImageView+WebCache.h"
#import "ZWYNetTool.h"
#import "BannerRootClass.h"
#import "BannerData.h"
#import "VCOfBannersWeb.h"
#import "OnePsychologyViewController.h"
#import "BaseNavigationController.h"
#define kUIScreenBounds [UIScreen mainScreen].bounds
@interface Album()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *albumCollectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSArray *sourceArray;
@property (nonatomic, strong) NSMutableArray *imageNames;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSMutableArray *urlOfImageArray;
@property (nonatomic, strong) BannerRootClass *bannerRootClass;
@end
@implementation Album
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self handleData];
        [self createCollection];
        [self createpageControl];
        [self addTimer];
    }
    return self;
}
#pragma mark - 数据处理
- (void)handleData{
    _urlOfImageArray = [NSMutableArray array];
    [ZWYNetTool GET:@"http://yiapi.xinli001.com/v2/yi/ad-list.json?name=yiapp-home-ad&key=e110509c8317557ef50ce777d107f4b3&v=1&_platform=android&sign=5307d8eba4ce6d1baca35f9b1db15e99&_version=4.0&token=0d4eeb8732f9ae2c73401002570ceb93" andBody:@"name=yiapp-home-ad&key=e110509c8317557ef50ce777d107f4b3&v=1&_platform=android&sign=5307d8eba4ce6d1baca35f9b1db15e99&_version=4.0&token=0d4eeb8732f9ae2c73401002570ceb93" andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _bannerRootClass = [BannerRootClass modelDic:result];
        for (BannerData *bannerData in _bannerRootClass.data) {
            [_urlOfImageArray addObject:bannerData.image];
        }
        [_urlOfImageArray addObject:[_bannerRootClass.data firstObject].image];
        [_urlOfImageArray insertObject:[_bannerRootClass.data lastObject].image atIndex:0];
        [self.albumCollectionView reloadData];
    } andFailureBlock:^(NSError *error) {
        
    }];
}
#pragma mark - 创建pageControl
- (void)createpageControl{
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.bounds) / 4, CGRectGetHeight(self.bounds) - 50, CGRectGetWidth(self.bounds) / 2, 40)];
    [self addSubview:_pageControl];
    [_pageControl addTarget:self action:@selector(handlepage:) forControlEvents:UIControlEventValueChanged];
}
#pragma mark - 创建CollectionView
- (void)createCollection{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = self.bounds.size;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 0;
    _albumCollectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    _albumCollectionView.contentOffset = CGPointMake(kUIScreenBounds.size.width, 0);
    _albumCollectionView.backgroundColor = [UIColor whiteColor];
    _albumCollectionView.pagingEnabled = YES;
    [self addSubview:_albumCollectionView];
    _albumCollectionView.delegate = self;
    _albumCollectionView.dataSource = self;
    [_albumCollectionView registerClass:[ImageViewCollectionViewCell class] forCellWithReuseIdentifier:@"ImageViewCollectionViewCell"];
}
#pragma mark - 创建定时器
- (void)addTimer{
    // 仅仅是创建,并没有加入runloop中
    // timer方法得加上runloop才能动
    self.timer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    // modes代表了多种的状态,就是默认状态和滚动状态,当放下tableView上面的时候,上面的定时器也能走
    // NSRunLoopCommonModes 和 NSDefaultRunLoopMode
    // 后者代表默认的状态,scheduledTimerWithTimeInterval是默认的
    // 前者是默认状态和滑动状态
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}
#pragma 定时器方法,下一个图片
- (void)nextImage{
    int page = (int)_pageControl.currentPage;
//    if (page == _urlOfImageArray.count - 2){
//        page = 0;
//    }
    page++;
    CGFloat x = page * kUIScreenBounds.size.width + kUIScreenBounds.size.width;
    _albumCollectionView.contentOffset = CGPointMake(x, 0);
}
#pragma mark - collectionView 代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    _pageControl.numberOfPages = _urlOfImageArray.count - 2;
    return _urlOfImageArray.count;
}
#pragma mark - cell的赋值
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ImageViewCollectionViewCell *cell = [collectionView    dequeueReusableCellWithReuseIdentifier:@"ImageViewCollectionViewCell" forIndexPath:indexPath];
    [cell.myImageView sd_setImageWithURL:_urlOfImageArray[indexPath.row] placeholderImage:[UIImage imageNamed:@"0"]];
    return cell;
}
#pragma mark - 滑动的时候实现的方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x < kUIScreenBounds.size.width) {
        [_albumCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_urlOfImageArray.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if(scrollView.contentOffset.x > (_urlOfImageArray.count - 2) * [UIScreen mainScreen].bounds.size.width) {
        [_albumCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    _pageControl.currentPage = scrollView.contentOffset.x / kUIScreenBounds.size.width - 1;
}
#pragma mark - 滑动完成时的方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    //计算页码
    CGFloat scrolleViewWidth = scrollView.frame.size.width;
    CGFloat x = scrollView.contentOffset.x;
    int page = x / scrolleViewWidth - 1;
    if (page == _bannerRootClass.data.count) {
        page = 0;
    }
    _pageControl.currentPage = page;
}
#pragma mark - page点击方法
- (void)handlepage:(UIPageControl *)page{
    [self.albumCollectionView setContentOffset:CGPointMake(CGRectGetWidth(kUIScreenBounds) * (_pageControl.currentPage + 1), 0) animated:YES];
}
#pragma mark - 移除定时器
- (void)removeTimer
{
    [_timer invalidate];
    _timer = nil;
}
#pragma mark - 开始拖拽视图
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
{
    //开始手动拖拽的时候移除定时器
    [self removeTimer];
}
#pragma mark - 完成拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
{
    //手动拖拽的时候添加定时器
    [self addTimer];
}
#pragma mark - CollectionView 被点击的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    VCOfBannersWeb *vcOfBannersWeb = [[VCOfBannersWeb alloc] init];
    vcOfBannersWeb.stringURL = @"http://yiapi.xinli001.com/v2/yi/gkk-list-page?token=0d4eeb8732f9ae2c73401002570ceb93&_platform=android&_version=4.0";
    BaseNavigationController *navigationController = [[BaseNavigationController alloc] initWithRootViewController:vcOfBannersWeb];
    OnePsychologyViewController *onePsychologyViewController = (OnePsychologyViewController *)self.nextResponder.nextResponder.nextResponder.nextResponder;
    [onePsychologyViewController presentViewController:navigationController animated:YES completion:^{
        
    }];
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end


@interface ImageViewCollectionViewCell()
@end
@implementation ImageViewCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _myImageView = [[UIImageView alloc] initWithFrame:frame];
        [self.contentView addSubview:_myImageView];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    _myImageView.frame = CGRectMake(0, 0, self.contentView.bounds.size.width, self.bounds.size.height);
}
@end
